import { createRouter, createWebHistory } from 'vue-router'
// @ts-ignore
import BasicLayout from '@/layouts/BasicLayout.vue'
import Login from '@/views/Login.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录页面独立于布局之外
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        requiresAuth: false
      }
    },
    // 需要布局的页面
    {
      path: '/',
      component: BasicLayout,
      redirect: '/',
      meta: {
        requiresAuth: true  // 需要认证
      },
      children: [
        {
          path: '',
          name: 'Home',
          // @ts-ignore
          component: () => import('@/views/Home.vue')
        },
        {
          path: 'users',
          name: 'Users',
          component: () => import('@/views/user/UserList.vue')
        },
        {
          path: 'products',
          name: 'Products',
          component: () => import('@/views/product/ProductList.vue')
        },
        {
          path: 'categories',
          name: 'Categories',
          component: () => import('@/views/category/CategoryList.vue')
        },
        {
          path: 'products/:id',
          name: 'ProductDetail',
          component: () => import('@/views/product/ProductDetail.vue')
        },
        {
          path: 'profile',
          name: 'Profile',
          component: () => import('@/views/user/UserProfile.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'order',
          name: 'Order',
          component: () => import('@/views/order/OrderList.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'after-sales',
          name: 'AfterSales',
          component: () => import('@/views/afterSales/AfterSalesList.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'coupons',
          name: 'Coupons',
          component: () => import('@/views/coupon/CouponList.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'user-coupons',
          name: 'UserCoupons',
          component: () => import('@/views/coupon/UserCouponList.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'carousel',
          name: 'Carousel',
          component: () => import('@/views/carousel/CarouselList.vue'),
          meta: {
            requiresAuth: true
          }
        }
      ]
    },
    // 404 页面
    {
      path: '/:pathMatch(.*)*',
      redirect: '/login'
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = sessionStorage.getItem('token')
  
  // 检查是否需要认证但没有token
  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  } 
  
  // 已登录用户访问登录页，重定向到首页
  if (token && to.path === '/login') {
    next('/')
    return
  }
  
  // 导入用户角色常量和用户存储
  if (token) {
    const { USER_ROLE } = await import('@/constants/user')
    const { useUserStore } = await import('@/stores/user')
    const userStore = useUserStore()
    
    // 确保已获取用户信息
    if (!userStore.userInfo) {
      await userStore.fetchUserInfo()
    }
    
    const userRole = userStore.userInfo?.userRole
    
    // 根据用户角色控制页面访问权限
    if (userRole === USER_ROLE.ADMIN) {
      // 管理员不能访问首页，直接重定向到商品列表页
      if (to.path === '/') {
        next('/products')
        return
      }
    } else if (userRole === USER_ROLE.FARMER) {
      // 农户不能访问分类管理、营销管理和用户管理页面
      if (to.path === '/categories' || 
          to.path.startsWith('/coupons') || 
          to.path.startsWith('/user-coupons') || 
          to.path.startsWith('/carousel') || 
          to.path === '/users') {
        next('/')
        return
      }
    }
  }
  
  // 其他情况正常放行
  next()
})

export default router
